<?php

namespace StudyBuddy\Controllers;
use \StudyBuddy\AccessException;
use \StudyBuddy\Responder;
use \StudyBuddy\Question;

use StudyBuddy\WebPage;

/**
 * Controller for making question (or thread)
 * Sticky
 *
 */
class Stick extends WebPage
{
	protected $membersOnly = true;

	protected $permission = 'make_sticky';

	protected $aRequired = array('qid');

	protected $oQuestion;

	protected function main(){
		$this->getQuestion()
		->setSticky()
		->redirect();
	}


	/**
	 * Get data for one question
	 * and create this->oQuestion object
	 *
	 * @throws \StudyBuddy\Exception if question not found
	 * in database
	 */
	protected function getQuestion(){
		$a = $this->oRegistry->Mongo->QUESTIONS->findOne(array('_id' => $this->oRequest['qid']));
		if(empty($a)){
			throw new \StudyBuddy\Exception('Question not found by id: '.$this->oRequest['qid']);
		}

		$this->oQuestion = new Question($this->oRegistry, $a);

		return $this;
	}

	/**
	 * Set i_sticky attribute of Question object
	 *
	 * @return object $this
	 */
	protected function setSticky(){
		$this->oQuestion['i_sticky'] = 1;
		$this->oQuestion->touch()->save();

		return $this;
	}

	/**
	 * Redirect back to the question page
	 *
	 */
	protected function redirect(){
		Responder::redirectToPage($this->oQuestion->getUrl());
	}

}